/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    void flatten(TreeNode *root)
    {
        if (root == nullptr)
        {
            return;
        }
        TreeNode listHead;
        TreeNode *pListHead = &listHead;
        preOrder(root, pListHead);
        root->left = nullptr;
        root->right = listHead.right->right;
    }

    void preOrder(TreeNode *tree, TreeNode *&list)
    {
        if (tree == nullptr)
        {
            return;
        }
        list->right = new TreeNode(tree->val);
        list = list->right;
        preOrder(tree->left, list);
        preOrder(tree->right, list);
    }
};